<?php


namespace app\unify\model;


use think\annotation\model\relation\BelongsToMany;
use think\Model;
use think\model\concern\SoftDelete;

class Menu extends Base
{
    const STATUS_DISABLE = 0;
    const STATUS_ENABLE = 1;

    const STATUS_LIST = [
        self::STATUS_ENABLE => '启用',
        self::STATUS_DISABLE => '禁用'
    ];

    const TARGET_SELF = "_self";
    const TARGET_BLANK = '_blank';
    const TARGET_LIST = [
        self::TARGET_SELF => '当前窗口',
        self::TARGET_BLANK => '新窗口'
    ];
    const DEBUG_TRUE = 1;
    const DEBUG_FALSE = 0;
    const DEBUG_LIST = [
        self::DEBUG_TRUE => '是',
        self::DEBUG_FALSE => '否',
    ];


    const TYPE_GROUP = 'group';
    const TYPE_MENU_PAGE = 'menu_page';
    const TYPE_PAGE = 'page';
    const TYPE_MENU_LINK = 'menu_link';

    const TYPE_LIST = [
        self::TYPE_GROUP => '分组',
        self::TYPE_MENU_PAGE => '菜单页面',
        self::TYPE_PAGE => '页面',
        self::TYPE_MENU_LINK => '菜单外链'
    ];
    const DEFAULT_MODULE = "unify";

    /**
     * @Notes 过滤匹配菜单
     * @Author EdwardCho
     * @Date 2024/1/4
     * @Time 00:18
     * @Interface filterMenuTree
     * @param array $menuList
     * @param array $authIds
     */
    public static function filterMenuTree(array $menuList = [], array|bool $authIds = [])
    {
        $filteredMenu = [];

        foreach ($menuList as $menu) {

            $menu['children'] = self::filterMenuTree($menu['children'] ?? [], $authIds);

            $flag1 = !empty($menu['children']);
            $flag2 = $authIds === true;
            // 如果节点的 authIds 和总的 authIds 有交集，保留该节点
            if (!$flag2) {
                $flag3 = array_intersect($menu['authIds'], $authIds);
            }

            if ($flag1 || $flag2 || $flag3) {
                $filteredMenu[] = $menu;
            }
        }

        return $filteredMenu;

    }

    public function auths()
    {
        return $this->belongsToMany(
            Auth::class,
            MenuAuth::class,
            'auth_id',
            'menu_id'
        );
    }


    public function authIds()
    {
        return $this->hasMany(MenuAuth::class, 'menu_id', 'id');
    }

    public function getTypeNameAttr($value, $data)
    {
        return self::TYPE_LIST[$data['type']] ?? '';
    }

    public function getStatusNameAttr($value, $data)
    {
        return self::STATUS_LIST[$data['status']] ?? '-';
    }

    public function getPidAttr($value, $data)
    {
        return strval($value);
    }


    public static function onBeforeDelete(Model $model): bool
    {

        if (self::where([
            'pid' => $model->getData($model->getPk())
        ])->find()) {
            throw new \Exception('请先移除下级菜单。');
        }


        return true;
    }


}